package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate redisTemplate;

    /**
     * 查询所有商铺类型
     *
     * @return
     */
    @Override
    public List<ShopType> queryList() {
       /*
       使用opsForList
        // 查询缓存
         String json = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_LIST_KEY);

        // 缓存是否存在
        if (StrUtil.isNotBlank(json)) {
            // 缓存存在,直接返回
            return JSONUtil.toList(json, ShopType.class);
        }
        // 写入缓存
        // redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_LIST_KEY, JSONUtil.toJsonStr(list));

        */

        List<String> range = redisTemplate.opsForList().range(RedisConstants.CACHE_SHOP_LIST_KEY, 0, -1);
        if (CollectionUtil.isNotEmpty(range)) {
            return range.stream().map(json -> JSONUtil.toBean(json, ShopType.class)).collect(Collectors.toList());
        }
        // 查询数据库
        List<ShopType> list = query().list();
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 写入缓存
        List<String> stringList = list.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        redisTemplate.opsForList().leftPushAll(RedisConstants.CACHE_SHOP_LIST_KEY, stringList);
        redisTemplate.expire(RedisConstants.CACHE_SHOP_LIST_KEY, Duration.ofHours(1L));
        //返回数据
        return list;
    }
}
